import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Menu } from 'antd'
import * as Icon from '@ant-design/icons'

import menuConfig from '../../config/menuConfig'
import logo from '../../assets/images/logo.png'
import './index.less'

const { SubMenu } = Menu

class LeftNav extends Component {
  /**
   * 动态渲染 VDOM Icon
   */
  vdomIcon = (name) => {
    return React.createElement(Icon[name])
  }

  /**
   * 路由循环 笨方法
   * 对传入的路由对象进行判断，并返回对应的路由
   */
  menuDispose = (routeObj) => {
    const { icon } = routeObj
    if (!routeObj.children) {
      return (
        <Menu.Item key={routeObj.path} icon={this.vdomIcon(icon)}>
          <Link to={routeObj.path}>{routeObj.title}</Link>
        </Menu.Item>
      )
    } else {
      return (
        <SubMenu
          key={routeObj.path}
          icon={this.vdomIcon(icon)}
          title={routeObj.title}
        >
          {routeObj.children.map((subItem) => this.menuDispose(subItem))}
        </SubMenu>
      )
    }
  }

  /**
   * 路由循环 优化
   * 上述方法涉及到循环还需要再手动写入，不方便
   */
  menuDisposeOpt = (menuList) => {
    return menuList.map((routeObj) => {
      const { icon } = routeObj
      if (!routeObj.children) {
        return (
          <Menu.Item key={routeObj.path} icon={this.vdomIcon(icon)}>
            <Link to={routeObj.path}>{routeObj.title}</Link>
          </Menu.Item>
        )
      } else {
        const { path } = routeObj
        const { pathname } = this.props.location
        this.pathname = pathname
        this.openKey = pathname.includes(path) ? path : ''

        return (
          <SubMenu
            key={routeObj.path}
            icon={this.vdomIcon(icon)}
            title={routeObj.title}
          >
            {this.menuDisposeOpt(routeObj.children)}
          </SubMenu>
        )
      }
    })
  }

  render() {
    const menuVOM = this.menuDisposeOpt(menuConfig)

    return (
      <div className="left-nav">
        <header className="left-nav-header">
          <img src={logo} alt="logo" />
          <span>清大后台</span>
        </header>
        <Menu
          defaultOpenKeys={[this.openKey]}
          selectedKeys={[this.pathname]}
          mode="inline"
          theme="dark"
        >
          {/* 笨方法 */}
          {/* {menuConfig.map((item) => this.menuDispose(item))} */}
          {/* 优化 */}
          {menuVOM}
        </Menu>
      </div>
    )
  }
}

export default withRouter(LeftNav)
